/**
 * Created by teddy on 15-12-28.
 */

// 取URL参数
function getUrlParam(name) {
    //构造一个含有目标参数的正则表达式对象
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    //匹配目标参数
    var r = window.location.search.substr(1).match(reg);
    //返回参数值
    if (r != null) return unescape(r[2]); return null;
}

var columnOptions = {
    chart: {
        renderTo: 'columnChart',
        type: 'bar'
    },
    colors: ['#50B432','#ED561B'],
    title: {
        text: 'Case Success Rate'
    },

    xAxis: {
        categories: [],
        labels: {
            style: {
                color: "#000000",
                fontSize: '14px',
                fontWeight: '600',
                fontFamily: ''
            }
        }
    },

    yAxis: {
        allowDecimals: true,
        min: 0,
        title: {
            text: ''
        }
    },
    tooltip: {
        formatter: function () {
            var s = '<b style="font-size:14px;font-weight:800">' + this.x + '</b>';
            $.each(this.points, function (i,point) {
                /*For Debug*/
                /*console.log(point);*/
                s += '<br/>' + '<span style="font-size:14px;color:' +point.color + '">' + point.series.name + '</span>: <b>' + point.y + '</b> (' + parseFloat(point.percentage).toFixed(2) + '%)<br/>';
            });

            return s;
        },
        shared: true
    },
    plotOptions: {
        series: {
            stacking: 'percent'
        }
    },
    credits: {
        enabled: false
    },
    series: [{
        name: 'Success',
        stack: 'male'
    }, {
        name: 'Fail',
        stack: 'male'
    }]
}

var averageChartOption = {

    chart: {
        type: 'column',
        renderTo: 'averageChart'
    },
    title: {
        text: 'Case Average Latency'
    },
    subtitle: {
        text: ''
    },
    xAxis: {
        type: 'category',
        labels: {
            rotation: -45,
            style: {
                fontSize: '13px',
                fontFamily: 'Verdana, sans-serif'
            }
        }
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Latency (ms)'
        }
    },
    legend: {
        enabled: false
    },
    tooltip: {
        pointFormat: '<b>{point.y:.1f} ms</b>'
    },
    credits: {
        enabled: false
    },
    series: [{
        name: 'Latency',
        data: [],
        dataLabels: {
            enabled: true,
            rotation: -90,
            color: '#FFFFFF',
            align: 'right',
            format: '{point.y:.1f}', // one decimal
            y: -80, // 10 pixels down from the top
            style: {
                fontSize: '13px',
                fontFamily: 'Verdana, sans-serif'
            }
        }
    }]
}



$(function () {
    var jobID = getUrlParam('jobid');
    var status = getUrlParam('status');
    if(status == 1) {
        $('.info-box').addClass("bg-green");
    }
    else {
        $('.info-box').addClass("bg-red");
    }

    $('#JobIDLabel').html(jobID);
    $('#CaseTable').bootstrapTable({
        url: 'getTestCaseByJobID.php?jobid=' + jobID
    });

    var xName = [];
    var successData = [];
    var failData = [];

    $.ajax({
        type: "GET",
        url: "getColumnChartData.php?jobid=" + jobID,
        success: function(tsv) {
            tsv = tsv.split(/\n/g);
            jQuery.each(tsv, function(i, line) {
                line = line.split(/\t/);

                if(line[0] != "") {
                    if ($.inArray(line[0], xName) < 0) {
                        xName.push(line[0]);
                    }
                }

                // case name
                //alert (line[0]);
                // case success or fail
                //alert (line[1]);
                // count
                //alert (line[2]);

                /*var date = Date.parse(line[0] + ' UTC');
                successData.push([date, parseInt(line[1].replace(',', ''), 10)]);
                failData.push([date, parseInt(line[2].replace(',', ''), 10)]);

                successCount = successCount + parseInt(line[1]);
                failCount = failCount + parseInt(line[2]);*/

            });
            //jQuery.each(tsv, function(i, line) {
            //
            //    line = line.split(/\t/);
            //
            //    jQuery.each(xName, function (x, name){
            //        if(name == line[0]) {
            //            if (line[1] == "Success") {
            //                if (line[2] != null) {
            //                    successData.push(parseInt(line[2],10));
            //                    failData.push(0);
            //                }
            //                else {
            //                    successData.push(0);
            //                }
            //            }
            //            else {
            //                if (line[2] != null) {
            //                    failData.push(parseInt(line[2],10));
            //                    successData.push(0);
            //                }
            //                else {
            //                    failData.push(0);
            //                }
            //            }
            //        }
            //    });
            //});

            jQuery.each(xName, function(i, name) {

                var successNumber = 0;
                var failNumber = 0;

                jQuery.each(tsv, function (x, line){

                    line = line.split(/\t/);

                    if(name == line[0]) {

                        if (line[1] == "Success") {

                            successNumber = parseInt(line[2],10);

                        }
                        else {
                            failNumber = parseInt(line[2],10);
                        }
                    }
                });
                failData.push(failNumber);
                successData.push(successNumber);

            });

            columnOptions.xAxis.categories = xName;
            columnOptions.series[0].data = successData;
            columnOptions.series[1].data = failData;
            var columnChart = new Highcharts.Chart(columnOptions);
        }
    })


    var xxName = [];
    var xsuccessData = [];

    // Get Latency Chart
    $.ajax({
        type: "GET",
        url: "getTestLatencyData.php?jobid=" + jobID,
        success: function(tsv) {
            tsv = tsv.split(/\n/g);
            jQuery.each(tsv, function(i, line) {
                line = line.split(/\t/);

                if(line[0] != "") {
                    if ($.inArray(line[0], xxName) < 0) {
                        xxName.push(line[0]);
                        xsuccessData.push(parseInt(line[1]));
                    }
                }

            });


            averageChartOption.xAxis.categories = xxName;
            averageChartOption.series[0].data = xsuccessData;
            var averageChart = new Highcharts.Chart(averageChartOption);
        }
    })

})

function detailFormatter(index, row)
{
    var result = "";
    $.each(row, function (key, value)
    {
        if(key == 'header')
        {
            result = "<b>Response Header:</b>" + "\n" + value;
        }
        if(key == 'body')
        {
            var sJSON = value;
            if (sJSON.length > 0)
            {
                try
                {
                    var oJSON = JSON.parse(sJSON);
                    result = result + "\n" + "<b>Response Body:</b>" + "\n" + FormatJSON(oJSON);
                }
                catch(sError)
                {
                    /*if NOT json format*/
                    result = result + "\n" + "<b>Response Body:</b>" + "\n" + value;
                }
            }
            else
            {
                alert("NULL");
            }
        }
    });
    return result;
}

function FormatJSON(oData, sIndent) {
    if (arguments.length < 2) {
        var sIndent = "";
    }
    var sIndentStyle = "    ";
    var sDataType = RealTypeOf(oData);

    // open object
    if (sDataType == "array") {
        if (oData.length == 0) {
            return "[]";
        }
        var sHTML = "[";
    } else {
        var iCount = 0;
        $.each(oData, function() {
            iCount++;
            return;
        });
        if (iCount == 0) {
            // object is empty
            return "{}";
        }
        var sHTML = "{";
    }

    // loop through items
    var iCount = 0;
    $.each(oData, function(sKey, vValue) {
            if (iCount > 0) {
                sHTML += ",";
            }
            if (sDataType == "array") {
                sHTML += ("\n" + sIndent + sIndentStyle);
            } else {
                sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": ");
            }

            // display relevant data type
            switch (RealTypeOf(vValue)) {
                case "array":
                case "object":
                    sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
                    break;
                case "boolean":
                case "number":
                    sHTML += vValue.toString();
                    break;
                case "null":
                    sHTML += "null";
                    break;
                case "string":
                    sHTML += ("\"" + vValue + "\"");
                    break;
                default:
                    sHTML += ("TYPEOF: " + typeof(vValue));                                                                                              }
            // loop
            iCount++;
        }
    )

    // close object
    if (sDataType == "array") {
        sHTML += ("\n" + sIndent + "]");
    } else {
        sHTML += ("\n" + sIndent + "}");
    }
    // return
    return sHTML;
}

function RealTypeOf(v) {
    if (typeof(v) == "object") {
        if (v === null) return "null";
        if (v.constructor == (new Array).constructor) return "array";
        if (v.constructor == (new Date).constructor) return "date";
        if (v.constructor == (new RegExp).constructor) return "regex";
        return "object";
    }
    return typeof(v);
}

function rowStyle(row, index) {
    var classes = ['active', 'success', 'info', 'warning', 'danger'];
    if (row["rc"] == 200) {
        return {
            classes: classes[1]
        };
    }
    else  if (row["rc"] == 80003) {
        return {
            classes: classes[3]
        };
    }
    else if (row["rc"] >= 400 )
    {
        return {
            classes: classes[4]
        };
    }

    return {};
}
